package com.ebeijia.service.user.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ebeijia.common.CommonCodeDefine;
import com.ebeijia.common.CommonConstant;
import com.ebeijia.dto.HomSourceDto;
import com.ebeijia.dto.OrderInfoDto;
import com.ebeijia.exception.ServiceException;
import com.ebeijia.mybatis.mapper.HomeSourceInfoMapper;
import com.ebeijia.mybatis.mapper.OrderInfoMapper;
import com.ebeijia.mybatis.mapper.UserInfoMapper;
import com.ebeijia.mybatis.pojo.HomeSourceInfo;
import com.ebeijia.mybatis.pojo.OrderInfo;
import com.ebeijia.mybatis.pojo.UserInfo;
import com.ebeijia.pay.PayResult;
import com.ebeijia.service.pay.impl.PayhandleServiceImpl;
import com.ebeijia.service.user.UserService;
import com.ebeijia.util.LoggerUtil;
import com.ebeijia.web.ResponseMessage;

@Service("userService")
public class UserServiceImpl extends PayhandleServiceImpl implements
		UserService {

	@Autowired
	private UserInfoMapper userInfoMapper;
	@Autowired
	private HomeSourceInfoMapper homeSourceMapper;
	@Autowired
	private OrderInfoMapper orderInfoMapper;

	/**
	 * 绑定用户信息
	 * 
	 * @return User
	 * @param id
	 */
	public UserInfo getUserId(String userNo) {

		return userInfoMapper.getUserId(userNo);
	}

	@Override
	@Transactional
	public void insert(UserInfo user) {

		userInfoMapper.insert(user);

	}

	@Override
	public UserInfo getUserByopenId(String openId) {
		return userInfoMapper.getUserByopenId(openId);

	}

	@Override
	public List<Map<String, Object>> TestCURSOR(Map<String, Object> map) {

		return userInfoMapper.TestCURSOR(map);
	}

	@Override
	public List<UserInfo> getOpenId(String openId) {

		return userInfoMapper.getOpenId(openId);
	}

	@Override
	@Transactional
	public ResponseMessage bindUserHome(UserInfo userInfo)
			throws ServiceException {
		Map params = new HashMap();
		params.put("userCode", userInfo.getUserNo());
		HomSourceDto homeSourceDto = queryUserInfoFrom(params);
		if (homeSourceDto == null) {
			return ResponseMessage.error("账户不存在");
		}
		if (!userInfo.getPhoneNo().equals(homeSourceDto.getHsPhoneNo())
				/*|| !userInfo.getIdNo().equals(homeSourceDto.getIdNo())*/) {
			return ResponseMessage.error("手机号不正确");
		}
		params = new HashMap();
		params.put("openId", userInfo.getOpenId());
		params.put("userNo", userInfo.getUserNo());

		UserInfo userInfoTmp = userInfoMapper.selectByParams(params);
		if (userInfoTmp != null) {
			return ResponseMessage.error("已绑定过此户，请勿重复绑定");
		}
		HomeSourceInfo newHomeSourceInfo = new HomeSourceInfo();
		BeanUtils.copyProperties(homeSourceDto, newHomeSourceInfo);
		userInfo.setUserName(homeSourceDto.getHsUserName());
		userInfo.setBindDate(new Date());

		userInfoMapper.insert(userInfo);

		newHomeSourceInfo.setUserId(userInfo.getId());
		newHomeSourceInfo.setHsUserNo(userInfo.getUserNo());
		homeSourceMapper.insert(newHomeSourceInfo);
		return ResponseMessage.success(userInfo);
	}

	/**
	 * 调用接口查询已存在用户账户信息
	 * 
	 * @param params
	 * @return
	 */
	private HomSourceDto queryUserInfoFrom(Map params) {
		HomSourceDto homeSourceInfo = new HomSourceDto();
		homeSourceMapper.queryUserInfoByPkg(params);
		LoggerUtil.info("queryUserInfoFrom :queryUserInfoByPkg " + params);
		String result = String.valueOf(params.get("result"));
		if ("0".equals(result) || params.get("houseNo") == null) {
			return null;
		}
		homeSourceInfo.setHsAddress(String.valueOf(params.get("areaAddress")));
		homeSourceInfo.setHsAreaName(String.valueOf(params.get("areaName")));
		homeSourceInfo.setBuildingName(String.valueOf(params
				.get("buildingName")));
		homeSourceInfo.setHsRoomNo(String.valueOf(params.get("houseNo")));
		homeSourceInfo.setHsUserName(String.valueOf(params.get("userName")));
		homeSourceInfo.setBalanceAmt((BigDecimal) params.get("balanceAmt"));
		homeSourceInfo.setLastTotalFlux((Integer) params.get("lastTotalFlux"));
		homeSourceInfo.setLastProcessTime((Date) params.get("lastProcessTime"));
		homeSourceInfo.setIdNo(String.valueOf(params.get("idNo")));
		homeSourceInfo.setHsPhoneNo(String.valueOf(params.get("phoneNo")));
		homeSourceInfo.setHsName(homeSourceInfo.getHsAreaName()
				+ homeSourceInfo.getHsRoomNo());
		homeSourceInfo.setRes(homeSourceInfo.getIdNo());
		return homeSourceInfo;

	}

	@Override
	public HomSourceDto queryUserInfoFromPkg(String hsUserNo)
			throws ServiceException {
		Map params = new HashMap();
		params.put("userCode", hsUserNo);
		HomSourceDto homSourceDto = queryUserInfoFrom(params);
		if (homSourceDto != null) {
			homSourceDto.setHsUserNo(hsUserNo);
		}
		return homSourceDto;
	}

	@Override
	@Transactional
	public ResponseMessage addOrderWithPay(OrderInfoDto orderInfoDto)
			throws ServiceException {
		// 查询用户房源信息
		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryMap.put("openId", orderInfoDto.getOpenId());
		// 获取用户信息
		UserInfo userInfo = userInfoMapper.selectByParams(queryMap);

		if (userInfo == null) {
			return ResponseMessage.error("未绑定的用户");
		}

		queryMap.put("hsUserNo", orderInfoDto.getUserNo());
		queryMap.put("userId", userInfo.getId());
		/*HomeSourceInfo sourceInfo = homeSourceMapper.selectByParams(queryMap);
		// 本地不存在，获取房源
		if (sourceInfo == null) {
			queryMap = new HashMap<String, Object>();
			queryMap.put("userCode", orderInfoDto.getUserNo());

			HomSourceDto homSourceDto = queryUserInfoFrom(queryMap);
			sourceInfo = new HomeSourceInfo();
			BeanUtils.copyProperties(homSourceDto, sourceInfo);
			sourceInfo.setUserId(userInfo.getId());
			sourceInfo.setHsUserNo(orderInfoDto.getUserNo());
			homeSourceMapper.insertSelective(sourceInfo);
		}*/
		orderInfoDto.setUserId(userInfo.getId());
		orderInfoDto.setProDesc("任丘供水用户充值");
		orderInfoDto = this.addOrder(orderInfoDto);
		PayResult payResult = this.sentToPay(orderInfoDto);
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setId(orderInfoDto.getId());
		// 请求威富通支付 失败，致订单为支付终止，成功致订单为支付中
		if (CommonCodeDefine.ERROR_PAY_SUCCESS.getCode().equals(
				payResult.getStatus())) {
			orderInfo.setOrderStatus(CommonCodeDefine.PAYING.getCode());
		} else {
			orderInfo.setOrderStatus(CommonCodeDefine.PEND_PAY.getCode());
		}
		orderInfoMapper.updateByPrimaryKeySelective(orderInfo);
		orderInfoDto.setTokenId(payResult.getTokenId());

		return ResponseMessage.success(orderInfoDto);
	}

	@Override
	public ResponseMessage addNewHomeSource(UserInfo userInfo)
			throws ServiceException {
		Map params = new HashMap();
		UserInfo userInfoTmp = userInfoMapper.selectByPrimaryKey(userInfo
				.getId());

		if (userInfoTmp == null) {
			return ResponseMessage.error("未绑定用户");
		}
		// 重复添加
		params.put("userId", userInfo.getId());
		params.put("hsUserNo", userInfo.getUserNo());
		HomeSourceInfo tmpSoucreInfo = homeSourceMapper.selectByParams(params);
		if (tmpSoucreInfo != null) {
			return ResponseMessage.error("已添加过此房源");
		}

		params = new HashMap<>();
		params.put("userCode", userInfo.getUserNo());

		HomSourceDto homeSourceDto = queryUserInfoFrom(params);
		if (homeSourceDto == null) {
			return ResponseMessage.error("账户不存在");
		}
		if (!userInfo.getPhoneNo().equals(homeSourceDto.getHsPhoneNo())
				/*|| !userInfo.getIdNo().equals(homeSourceDto.getIdNo())*/) {
			return ResponseMessage.error("手机号不正确");
		}

		HomeSourceInfo newHomeSourceInfo = new HomeSourceInfo();
		BeanUtils.copyProperties(homeSourceDto, newHomeSourceInfo);

		newHomeSourceInfo.setUserId(userInfo.getId());
		newHomeSourceInfo.setHsUserNo(userInfo.getUserNo());
		homeSourceMapper.insert(newHomeSourceInfo);
		return ResponseMessage.success();
	}
}
